// 从网络上读取某个excel文件，url必须同域，否则报错
// readWorkbookFromRemoteFile('', (workbook) => {
//     console.log(workbook)
//     readWorkbook(workbook)
// })
import { i2s } from '@/utils/utils'
import _ from 'lodash'
// const Excel = require('exceljs')
import Vue from 'vue'
import { filtersFileUrl } from '@/filter/index'
const Excel = Vue.prototype.$Excel
import { WORK_KEY, FORMULA_KEY } from "@/utils/local";
export function getExcelWork(url) {
    console.log('filtersFileUrl(url) :>> ', url);
    return new Promise(async (resolve, reject) => {
        var xhr = new XMLHttpRequest();
        xhr.open('get', filtersFileUrl(url), true);
        xhr.responseType = 'arraybuffer';
        xhr.onload = function (e) {
            if (xhr.status == 200) {
                const workbook = new Excel.Workbook();
                workbook.xlsx.load(xhr.response).then(res => {
                    console.log('row1 :>> ', res);
                    res.eachSheet((_sheet, id) => {
                        console.log('row2 :>> ', _sheet);
                        _sheet.eachRow((row, rowIndex) => {
                            console.log('row3 :>> ', row);

                        })
                    })

                })
                // var data = new Uint8Array(xhr.response)
                // var workbook = XLSX.read(xhr.response, { type: 'binary' });

                // const buffer = await workbook.xlsx.writeBuffer();
            }
        };
        xhr.send();
    })
}
export function readWorkbookFromRemoteFile(url, parameter, technologyParameterLength, deviceInfoList, callback) {
    let clonedeviceInfoList = _.cloneDeep(deviceInfoList)

    parameter = parameter.concat({
        defaultValue: "",
        key: "设备类型",
        text: "[设备类型]",
        type: "5",
        unit: "",
        value: "设备类型",
        values: clonedeviceInfoList.map(m => {
            return {
                text: m.deviceTypeName,
                value: m.deviceTypeName
            }
        })
    })
    parameter = parameter.concat({
        defaultValue: "",
        key: "设备编号",
        text: "[设备编号]",
        type: "5",
        unit: "",
        value: "设备编号",
        values: clonedeviceInfoList.map(m => {
            return {
                text: m.deviceList.map(m => m.deviceName).join('\n'),
                value: m.deviceList.map(m => m.deviceName).join('\n')
            }
        })
    })
    var xhr = new XMLHttpRequest();
    xhr.open('get', filtersFileUrl(url), true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function (e) {
        if (xhr.status == 200) {
            const workbook = new Excel.Workbook();

            workbook.xlsx.load(xhr.response).then(res => {
                res.eachSheet((_sheet, id) => {
                    const worksheet = workbook.getWorksheet(id);
                    let devArr = []
                    _sheet.eachRow((row, rowIndex) => {
                        const { cells } = row.model
                        if (cells && cells.length !== 0) {
                            cells.forEach((item, index) => {
                                let note = worksheet.getCell(item.address).note
                                let note2 = worksheet.getCell(item.address).note


                                if (note && _.isString(note)) {
                                    // 先删除所有的设备
                                    // if (note2 == '{设备类型-设备参数}') {
                                    //     const fullAddress = _.cloneDeep(worksheet.getCell(item.address).fullAddress)
                                    //     let { col, row } = fullAddress
                                    //     // 记录存在的个数
                                    //     if (col == 1) {
                                    //         devArr.push(row)
                                    //     }
                                    // }
                                    note = note.split(':')
                                    console.log('clonedeviceInfoList2 :>> ', note[0]);
                                    if (note[0] == WORK_KEY) {
                                    }
                                    // if (note[0] == FORMULA_KEY) {
                                    // technologyParameterLength
                                    // 获取当前变量存在的单元格和下变的单元格
                                    const fullAddress = _.cloneDeep(worksheet.getCell(item.address).fullAddress)
                                    //数字转换字母
                                    let col = i2s(fullAddress.col)
                                    console.log('parameter :>> ', parameter);
                                    parameter.forEach(p => {
                                        // 放在循环里边,每次变量都要初始化,不然会一直递增
                                        let row = fullAddress.row - 1  //6
                                        p.values.forEach((v, i) => {
                                            row += 1
                                            v.address = `${col}${row}` //当前位置
                                            v.addressRow = row //当前行
                                        })
                                    })
                                    console.log('note[1] :>> ', note[1]);
                                    if (technologyParameterLength) {
                                        if (note[0] == FORMULA_KEY || note[1] == '[设备类型]' || note[1] == '[设备编号]') {
                                            let row = fullAddress.row - 1  //6
                                            for (let i = 0; i < technologyParameterLength; i++) {
                                                row += 1
                                                worksheet.getCell(`${col}${row}`).value = ''
                                            }
                                        }
                                    }


                                    // clonedeviceInfoList.forEach(p => {
                                    //     console.log('note[1] :>> ', note[1]);
                                    //     if (note[1] == `[设备类型]`) {
                                    //         worksheet.getCell(item.address).value = p.deviceTypeName
                                    //     }
                                    //     if (note[1] == `[设备编号]`) {
                                    //         worksheet.getCell(item.address).value = p.deviceList.map(m => m.deviceName).join(',')
                                    //     }
                                    // })
                                    parameter.forEach(p => {
                                        if (note[1] == `[${p.key}]`) {
                                            p.values.forEach(v => {
                                                worksheet.getCell(v.address).value = v.value
                                                // 添加边框
                                            })
                                        }
                                    })
                                }
                                // 删除批注
                                // Vue.set(item, 'comment', null)
                                // worksheet.getCell(item.address).note = null
                                // worksheet.getCell(item.address)._comment = null
                                // console.log(item, '测试===', worksheet.getCell(item.address))
                                // };
                            })

                        }

                    })
                    // 删除设备 
                    // if (devArr.length !== 0) {
                    //     // 删除一行之后下一行的行号会上移 比如设备第一行行号是20 删除第一行下边的会上移到20行

                    //     //解决办法 从设备的第一行开始删除  一次删除一行,
                    //     devArr.forEach(item => {
                    //         worksheet.spliceRows(devArr[0], 1)
                    //     })
                    // }
                    // //添加设备
                    // if (clonedeviceInfoList.length != 0) {
                    //     clonedeviceInfoList.unshift({
                    //         deviceTypeToken: '设备类型',
                    //         deviceList: ['设备参数']
                    //     })

                    //     clonedeviceInfoList.forEach(item => {
                    //         const newRow = worksheet.addRow([item.deviceTypeToken, item.deviceList.map(m => m.name).join('、')], 'i+');
                    //         newRow._cells.forEach(cell => {
                    //             if (worksheet.getCell(cell._address).value) {
                    //                 worksheet.getCell(cell._address).note = '{设备类型-设备参数}'


                    //             }
                    //         })
                    //     })
                    // }

                })
                if (callback) callback(workbook);
            })
            // var data = new Uint8Array(xhr.response)
            // var workbook = XLSX.read(xhr.response, { type: 'binary' });

            // const buffer = await workbook.xlsx.writeBuffer();
        }
    };
    xhr.send();
}
function getNexts() {

}